<?php
namespace app\common\service\ability\service;
use app\common\service\ability\interfaces\ResourceAbility;
use app\common\exception\TokenException;
use app\common\model\Resource;
use think\db\exception\DataNotFoundException;
use app\common\exception\LogicException;
//资源文件管理类
class ResourceAbilityService implements ResourceAbility{
    public function __construct(Resource $resource)
    {
        $this->models = $resource;
    }
    public function getListPage($where){
        $page = getPageData();
        $orderStr = getOrderString();
        $list = $this->models->where($where)->limit($page['start'], $page['limit'])->order($orderStr.'resource_id desc')->select();
        if ($list->isEmpty()) {
            throw new DataNotFoundException(lang('DATA_NOT_FOUND'), 10006);
        } else {
            $data['total'] = $this->models->where($where)->count();
            $data['list'] = $list;
            return $data;
        }
    }
    public function getCount($where){
        return $this->models->where($where)->count();
    }
    public function saveAdd($addData){
        $addData['last_time'] = time();
        $addData['status'] = 0;
        $result = $this->models->create($addData);
        if ($result !== false) {
            return $result;
        } else {
            throw new LogicException(lang('SAVE_ERROR'));
        }
    }
    public function getLine($where){
        $row = $this->models->where($where)->field('resource_id,group_id,resource_type,code,original_url,thumbnail_url')->find();
        if (empty($row)) {
            throw new DataNotFoundException(lang('DATA_NOT_FOUND'), 10006);
        } else {
            return $row;
        }
    }
    public function saveEdit($editData){
        $where[] = ['resource_id', '=', $editData['resource_id']];
        $resourceRow=$this->getLine($where);
        $result = $resourceRow->save($editData);
        if ($result !== false) {
            return $result;
        } else {
            throw new LogicException(lang('SAVE_ERROR'));
        }
    }
    public function saveDel($delData){
        $where[] = ['resource_id', '=', $delData['resource_id']];
        $resourceRow=$this->getLine($where);
        $result = $resourceRow->delete();
        if ($result !== false) {
            $this->deleteFile($resourceRow);
            return $result;
        } else {
            throw new LogicException(lang('DEL_ERROR'));
        }
    }
    public function setResourceStatus($resourceData){
        $where[] = ['code|original_url|thumbnail_url', '=', $resourceData['target']];
        $row = $this->getLine($where);
        if ($row) {
            $updateData['status'] = $resourceData['status'];
            $result = $this->models->where($where)->update($updateData);
            if ($result !== false) {
                return $result;
            } else {
                throw new LogicException(lang('SET_ERROR'));
            }
        } else {
            return [];
        }
    }
    public function uploadFile($fileData){
        $file=$fileData['file'];
        $type=$fileData['type'];
        $dirName = $this->getUploadDir($file->getOriginalExtension());
        $fileName = $this->getFileName($file);
        $saveName = \think\facade\Filesystem::disk('public')->putFileAs($dirName, $file, $fileName);
        $resourceData['original_url'] = \think\Facade\Filesystem::getDiskConfig('public', 'url').'/'.str_replace('\\', '/', $saveName);
        //如果是图片就生成缩略图
        if($type==1){
            $resourceData['thumbnail_url'] = $this->setThumbnailImg(\think\Facade\Filesystem::getDiskConfig('public', 'url').$dirName, $fileName);
        }else{
            $resourceData['thumbnail_url'] = "";
        }
        $resourceData['resource_type']=$type;
        $resourceData['code'] = md5($resourceData['original_url'].$resourceData['thumbnail_url']);
        $this->saveAdd($resourceData);
        return $resourceData;
    }
    public function getImgPath($resourceData){
        $where[] = ['code|original_url|thumbnail_url', '=', $resourceData['target']];
        $row = $this->getLine($where);
        if (empty($row)) {
            return [];
        } else {
            $editData['resource_id']=$row['resource_id'];
            $editData['last_time']=time();
            $this->saveEdit($editData);
            $row['original_url']=request()->domain(). $row['original_url'];
            $row['thumbnail_url']=request()->domain(). $row['thumbnail_url'];
            return $row;
        }
    }
    public function cleanUpExpiredFiles(){
        $expirationTime = 600;
        // $where[] = ['last_time', '<', time() - $expirationTime*100];
        $where[] = ['resource_type', '=', 1];
        $where[] = ['status', '=', 0];
        $list = $this->models->where($where)->select();
        if(!$list->isEmpty()){
            foreach ($list as $ve) {
                $this->saveDel($ve);
            }
        }
        return  $list;
    }
    public function deleteFile($resourceRow){
        if (!empty($resourceRow['original_url']) && is_file('.'.$resourceRow['original_url'])) {
            unlink('.'.$resourceRow['original_url']);
        }
        if (!empty($resourceRow['thumbnail_url']) && is_file('.'.$resourceRow['thumbnail_url'])) {
            unlink('.'.$resourceRow['thumbnail_url']);
        }
    }
    public function getUploadDir($type){
        return '/'.$type.'/'.date('Y-m-d');
    }
    public function getFileName($file){
        return date('H_i_s').rand(999, 999999).'_'.$file->getOriginalName();
    }
    public function setThumbnailImg($dirName, $fileName){
        $image = \think\Image::open('.'.$dirName.'/'.$fileName);
        $thumbUrl = $dirName.'/thumb_'.$fileName;
        $image->thumb(800, 800)->save('.'.$thumbUrl);
        return $thumbUrl;
    }
}